<route lang="yaml">
meta:
  title: 分类管理
</route>

<script lang="ts" setup>
import type { TabsPaneContext } from 'element-plus'
import { toast } from 'vue-sonner'
import apiCategory from '@/api/modules/category'

const router = useRouter()

const activeName = ref('first')
function handleClick(tab: TabsPaneContext, event: Event) {
  console.log(tab, event)
}

const radio = ref(3)

interface Category {
  id: number
  name: string
  title: string
  enabled: boolean
  createdAt: string
  children?: Category[]
}

const categories = ref<Category[]>([])
function normalize(list: any[]): Category[] {
  return (list || []).map((i: any) => ({
    id: Number(i.id ?? i.ID ?? 0),
    name: String(i.name ?? i.title ?? ''),
    title: String(i.template ?? i.subtitle ?? i.title ?? ''),
    enabled: typeof i.enabled !== 'undefined' ? Boolean(i.enabled) : (i.status === 1),
    createdAt: String(i.createdAt ?? i.create_time ?? i.created_at ?? ''),
    children: normalize(i.children ?? i.childrens ?? []),
  }))
}

async function fetchCategories() {
  const res = await apiCategory.index()
  categories.value = normalize(res.data || [])
}

onMounted(fetchCategories)

function isTopLevel(row: Category) {
  return categories.value.some(c => c.id === row.id)
}

function editCategory(row: Category) {
  apiCategory.edit({ id: row.id, name: row.name, title: row.title, enabled: row.enabled }).then(() => {
    toast.success('编辑成功')
    fetchCategories()
  })
}

function publishFields(row: Category) {
  toast.success(`发布字段：${row.name}`)
}
function feeSettings(row: Category) {
  toast.success(`付费设置：${row.name}`)
}
function deleteCategory(row: Category) {
  apiCategory.delete(row.id).then(() => {
    toast.success('删除成功')
    fetchCategories()
  })
}

function getActions(row: Category) {
  const all = [
    { key: 'edit', label: '编辑', handle: () => editCategory(row) },
    { key: 'add', label: '添加子项', handle: () => addChild(row) },
    { key: 'publish', label: '发布字段', handle: () => publishFields(row) },
    { key: 'fee', label: '付费设置', handle: () => feeSettings(row) },
    { key: 'delete', label: '删除', handle: () => deleteCategory(row) },
  ]
  const hasChildren = !!(row.children && row.children.length)
  if (isTopLevel(row) && hasChildren) {
    return all.filter(a => ['edit', 'add', 'delete'].includes(a.key))
  }
  return all
}

const addRootDrawerOpen = ref(false)
const addRootForm = reactive({
  agentAppId: 0,
  title: '',
  province_code: '',
  city_code: '',
  county_code: '',
  tag_ids: '',
  tag_ids_arr: [] as (string | number)[],
  status: '1',
  audit_status: 1,
  sorts: 0,
  address: '',
  content: '',
})
const appOptions = ref<{ label: string, value: number }[]>([])
const provinces = ref<{ label: string, value: string }[]>([])
const cities = ref<{ label: string, value: string }[]>([])
const counties = ref<{ label: string, value: string }[]>([])
const tagOptions = ref<{ label: string, value: string }[]>([])
watch(() => addRootForm.province_code, (val) => {
  addRootForm.city_code = ''
  addRootForm.county_code = ''
  if (val) {
    loadCities(val)
  }
})
watch(() => addRootForm.city_code, (val) => {
  addRootForm.county_code = ''
  if (val) {
    loadCounties(val)
  }
})
async function loadApps() {
  appOptions.value = [
    { label: '应用A', value: 1 },
    { label: '应用B', value: 2 },
  ]
}
async function loadTags() {
  tagOptions.value = [
    { label: '热门', value: 'hot' },
    { label: '推荐', value: 'recommend' },
    { label: '置顶', value: 'top' },
  ]
}
async function loadProvinces() {
  provinces.value = [
    { label: '北京', value: '110000' },
    { label: '上海', value: '310000' },
  ]
}
async function loadCities(province: string) {
  cities.value = province === '110000'
    ? [{ label: '北京市', value: '110100' }]
    : [{ label: '上海市', value: '310100' }]
}
async function loadCounties(city: string) {
  counties.value = city === '110100'
    ? [{ label: '朝阳区', value: '110105' }, { label: '海淀区', value: '110108' }]
    : [{ label: '浦东新区', value: '310115' }, { label: '徐汇区', value: '310104' }]
}

const addDrawerOpen = ref(false)
const addForm = reactive({ name: '', title: '' })
const currentParent = ref<Category | null>(null)
function handleAddConfirm() {
  if (!currentParent.value) {
    return
  }
  apiCategory.add({
    agent_app_id: addRootForm.agentAppId,
    category_id: currentParent.value.id,
    title: addForm.title || addForm.name,
    province_code: addRootForm.province_code,
    city_code: addRootForm.city_code,
    county_code: addRootForm.county_code,
    tag_ids: Array.isArray(addRootForm.tag_ids_arr) ? addRootForm.tag_ids_arr.join(',') : addRootForm.tag_ids,
    status: addRootForm.status,
    audit_status: addRootForm.audit_status,
    sorts: addRootForm.sorts,
    other_fields: [{ address: addRootForm.address, content: addRootForm.content }],
  }).then(() => {
    toast.success('添加成功')
    fetchCategories()
  })
  addDrawerOpen.value = false
  addForm.name = ''
  addForm.title = ''
}

function openAddRoot() {
  addRootDrawerOpen.value = true
  loadApps()
  loadTags()
  loadProvinces()
}
function handleAddRootConfirm() {
  apiCategory.add({
    agent_app_id: addRootForm.agentAppId,
    category_id: 0,
    title: addRootForm.title,
    province_code: addRootForm.province_code,
    city_code: addRootForm.city_code,
    county_code: addRootForm.county_code,
    tag_ids: Array.isArray(addRootForm.tag_ids_arr) ? addRootForm.tag_ids_arr.join(',') : addRootForm.tag_ids,
    status: addRootForm.status,
    audit_status: addRootForm.audit_status,
    sorts: addRootForm.sorts,
    other_fields: [{ address: addRootForm.address, content: addRootForm.content }],
  }).then(() => {
    toast.success('添加成功')
    fetchCategories()
  })
  addRootDrawerOpen.value = false
}

function addChild(row: Category) {
  addDrawerOpen.value = true
  currentParent.value = row
}
function gotoPublishManage() {
  router.push('/sort/publish_manage')
}
function gotoFeeManage() {
  router.push('/sort/fee_manage')
}

const periodUnitOptions = [
  { label: '月', value: 'month' },
  { label: '周', value: 'week' },
  { label: '日', value: 'day' },
]
const packageDaysOptions = [30, 60, 90]
const globalSettings = reactive({
  dailyTotal: 5,
  intervalMinutes: 0,
  categoryPerPeriodCount: 1,
  categoryPeriodUnit: 'day' as 'day' | 'week' | 'month',
  infoValidDays: 30,
  categoryDailyCap: 3,
  unitLabel: '单价',
  packages: [
    { name: '发布30天', price: 10, validDays: 30, banColor: '#ff0000', isDefault: true },
    { name: '发布60天', price: 20, validDays: 60, banColor: '#ff0000', isDefault: false },
    { name: '发布90天', price: 30, validDays: 90, banColor: '#ff0000', isDefault: false },
  ],
})
function addPackageRow() {
  globalSettings.packages.push({ name: '新增套餐', price: 5, validDays: 30, banColor: '#ff0000', isDefault: false })
}
function deletePackageRow(index: number) {
  globalSettings.packages.splice(index, 1)
}
function setDefaultPackage(index: number) {
  globalSettings.packages.forEach((r, i) => {
    r.isDefault = i === index
  })
}
function duplicatePackageRow(index: number) {
  const r = globalSettings.packages[index]
  globalSettings.packages.splice(index + 1, 0, { ...r, isDefault: false })
}
function saveGlobalSettings() {
  toast.success('已保存')
}
</script>

<template>
  <div>
    <FaPageMain>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="分类管理" name="first">
          <div class="shadow-demo">
            <!-- 卡片悬浮上浮+阴影 -->
            <el-card shadow="never">
              <el-radio-group v-model="radio">
                <el-radio :value="3">
                  全部
                </el-radio>
                <el-radio :value="6">
                  开启
                </el-radio>
                <el-radio :value="9">
                  关闭
                </el-radio>
              </el-radio-group>
              <!-- 功能 -->
            </el-card>
            <div class="fun-btn">
              <FaButton @click="openAddRoot">
                添加分类
              </FaButton>
              <FaButton @click="gotoPublishManage">
                发布管理
              </FaButton>
              <FaButton @click="gotoFeeManage">
                收费管理
              </FaButton>
              <!-- <FaButton>分类关联区域选择</FaButton> -->
            </div>
          </div>

          <el-table :data="categories" row-key="id" default-expand-all border style="width: 100%; margin-bottom: 20px;">
            <el-table-column label="分类名称" min-width="220">
              <template #default="scope">
                <span class="truncate">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="分类模板" min-width="180">
              <template #default="scope">
                {{ scope.row.title }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template #default="scope">
                <el-switch v-model="scope.row.enabled" @change="editCategory(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template #default="scope">
                {{ scope.row.createdAt }}
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="260" fixed="right">
              <template #default="scope">
                <div class="flex items-center gap-3 text-[13px]">
                  <template v-for="action in getActions(scope.row)" :key="action.key">
                    <a class="cursor-pointer text-primary" @click="action.handle">{{ action.label }}</a>
                  </template>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="全局设置" name="second">
          <div class="px-2 py-2 space-y-6">
            <div class="text-sm text-muted-foreground">
              此处为全局的设置，非单独分类或者子分类的，如果这里设置了，以这里为主。
            </div>

            <div class="text-base font-medium">
              发布数量设置
            </div>
            <div class="grid grid-cols-2 gap-6">
              <div class="min-w-0">
                <div class="mb-1 text-sm text-muted-foreground">
                  每天发布总量
                </div>
                <div class="flex items-center gap-2">
                  <el-input-number v-model="globalSettings.dailyTotal" :min="0" />
                  <span class="text-sm">条/天</span>
                </div>
                <div class="mt-1 text-xs text-muted-foreground">
                  用户每天总共能发布的条数；0为不限制；整体的发布次数，不受其他设置限制
                </div>
              </div>
              <div class="min-w-0">
                <div class="mb-1 text-sm text-muted-foreground">
                  发布间隔时间
                </div>
                <div class="flex items-center gap-2">
                  <el-input-number v-model="globalSettings.intervalMinutes" :min="0" />
                  <span class="text-sm">分钟</span>
                </div>
                <div class="mt-1 text-xs text-muted-foreground">
                  超过间隔时长，才可发布下一条信息
                </div>
              </div>
            </div>

            <div class="text-base font-medium">
              全分类设置
            </div>
            <div class="space-y-4">
              <div class="min-w-0">
                <div class="mb-1 text-sm text-muted-foreground">
                  单个分类可发布
                </div>
                <div class="flex flex-wrap items-center gap-2">
                  <el-input-number v-model="globalSettings.categoryPerPeriodCount" :min="0" />
                  <span class="text-sm">条</span>
                  <span class="text-sm">/</span>
                  <el-select v-model="globalSettings.categoryPeriodUnit" style="width: 120px;">
                    <el-option v-for="u in periodUnitOptions" :key="u.value" :label="u.label" :value="u.value" />
                  </el-select>
                  <span class="text-sm">，信息最大有效时长</span>
                  <el-input-number v-model="globalSettings.infoValidDays" :min="0" />
                  <span class="text-sm">天</span>
                </div>
                <div class="mt-1 text-xs text-muted-foreground">
                  0为不受限制，相关分类下或页面的置顶费用的次数；大于0，超过次数的置顶信息，将在当前分类下次置顶时用时；信息显露期、越过时效后，自动下架
                </div>
              </div>
              <div class="min-w-0">
                <div class="mb-1 text-sm text-muted-foreground">
                  单个分类每天发布总数上限
                </div>
                <div class="flex items-center gap-2">
                  <el-input-number v-model="globalSettings.categoryDailyCap" :min="0" />
                  <span class="text-sm">条</span>
                </div>
                <div class="text-danger mt-1 text-xs">
                  原特殊分类设置已取消，若需要单独设置，请前往分类——费用与权限中编辑
                </div>
              </div>
            </div>

            <div class="text-base font-medium">
              个人用户设置
            </div>
            <div class="space-y-3">
              <div class="grid grid-cols-12 items-center gap-3">
                <div class="col-span-3 text-sm text-muted-foreground">
                  套餐名称
                </div>
                <div class="col-span-2 text-sm text-muted-foreground">
                  付费价格
                </div>
                <div class="col-span-3 text-sm text-muted-foreground">
                  有效天数
                </div>
                <div class="col-span-2 text-sm text-muted-foreground">
                  封禁颜色
                </div>
                <div class="col-span-2 text-sm text-muted-foreground">
                  操作
                </div>
              </div>
              <div v-for="(p, i) in globalSettings.packages" :key="i" class="grid grid-cols-12 items-center gap-3">
                <div class="col-span-3">
                  <el-input v-model="p.name" />
                </div>
                <div class="col-span-2">
                  <el-input-number v-model="p.price" :min="0" />
                </div>
                <div class="col-span-3">
                  <el-select v-model="p.validDays" placeholder="选择天数">
                    <el-option v-for="d in packageDaysOptions" :key="d" :label="`${d}天`" :value="d" />
                  </el-select>
                </div>
                <div class="col-span-1">
                  <el-color-picker v-model="p.banColor" />
                </div>
                <div class="col-span-3 flex flex-wrap items-center gap-2">
                  <el-button size="small" @click="setDefaultPackage(i)">
                    {{ p.isDefault ? '默认' : '设为默认' }}
                  </el-button>
                  <el-button size="small" @click="duplicatePackageRow(i)">
                    复制插入
                  </el-button>
                  <el-button size="small" type="danger" @click="deletePackageRow(i)">
                    删除
                  </el-button>
                </div>
              </div>
              <div>
                <el-button size="small" type="primary" @click="addPackageRow">
                  新增
                </el-button>
              </div>
            </div>

            <div class="pt-2">
              <el-button type="primary" @click="saveGlobalSettings">
                保存
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </FaPageMain>
  </div>
  <FaDrawer v-model="addDrawerOpen" title="添加子项" show-cancel-button show-confirm-button confirm-button-text="确定" cancel-button-text="取消" @confirm="handleAddConfirm">
    <div class="grid grid-cols-2 gap-4 p-2">
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          名称
        </div>
        <FaInput v-model="addForm.name" class="w-full" />
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          模板
        </div>
        <FaInput v-model="addForm.title" class="w-full" />
      </div>
    </div>
  </FaDrawer>
  <FaDrawer v-model="addRootDrawerOpen" title="添加分类" show-cancel-button show-confirm-button confirm-button-text="确定" cancel-button-text="取消" @confirm="handleAddRootConfirm">
    <div class="grid grid-cols-2 gap-4 p-2">
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          信息标题
        </div>
        <el-input v-model="addRootForm.title" placeholder="请输入标题" />
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          应用
        </div>
        <el-select v-model="addRootForm.agentAppId" placeholder="选择关联应用">
          <el-option v-for="item in appOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          省代码
        </div>
        <el-select v-model="addRootForm.province_code" placeholder="选择省">
          <el-option v-for="p in provinces" :key="p.value" :label="p.label" :value="p.value" />
        </el-select>
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          市代码
        </div>
        <el-select v-model="addRootForm.city_code" :disabled="!addRootForm.province_code" placeholder="选择市">
          <el-option v-for="c in cities" :key="c.value" :label="c.label" :value="c.value" />
        </el-select>
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          区县代码
        </div>
        <el-select v-model="addRootForm.county_code" :disabled="!addRootForm.city_code" placeholder="选择区县">
          <el-option v-for="d in counties" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
      </div>
      <div class="col-span-2">
        <div class="mb-1 text-sm text-muted-foreground">
          标签
        </div>
        <el-select v-model="addRootForm.tag_ids_arr" multiple collapse-tags :max-collapse-tags="2" placeholder="选择标签">
          <el-option v-for="t in tagOptions" :key="t.value" :label="t.label" :value="t.value" />
        </el-select>
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          状态
        </div>
        <el-radio-group v-model="addRootForm.status">
          <el-radio label="1">
            正常
          </el-radio>
          <el-radio label="0">
            隐藏
          </el-radio>
        </el-radio-group>
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          审核状态
        </div>
        <el-radio-group v-model="addRootForm.audit_status">
          <el-radio :label="1">
            通过
          </el-radio>
          <el-radio :label="0">
            未通过
          </el-radio>
        </el-radio-group>
      </div>
      <div>
        <div class="mb-1 text-sm text-muted-foreground">
          排序
        </div>
        <el-input-number v-model="addRootForm.sorts" :min="0" />
      </div>
      <div class="col-span-2">
        <div class="mb-1 text-sm text-muted-foreground">
          地址
        </div>
        <el-input v-model="addRootForm.address" />
      </div>
      <div class="col-span-2">
        <div class="mb-1 text-sm text-muted-foreground">
          内容
        </div>
        <el-input v-model="addRootForm.content" type="textarea" />
      </div>
    </div>
  </FaDrawer>
</template>

<style scoped>
.shadow-demo {
  display: flex;
  gap: 10px;
  align-items: center;
  width: 100%;
  padding: 10px;
  margin-left: -10px;
}

/* 按钮悬浮阴影 */
.shadow-button {
  padding: 10px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgb(64 191 128 / 20%); /* 初始绿色阴影 */
  transition: all 0.3s ease; /* 统一过渡动画 */
}

.shadow-button:hover {
  box-shadow: 0 8px 16px rgb(64 191 128 / 30%); /* 悬浮增强阴影 */
  transform: translateY(-2px); /* 轻微上浮 2px */
}

/* 卡片悬浮上浮+阴影 */
.float-shadow-card {
  /* width: 100%; */
  padding: 20px;

  /* display: flex;
  align-items: center;
  justify-content: flex-start; */
  box-shadow: 0 6px 12px rgb(0 0 0 / 5%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* 缓动动画 */
}

.fun-btn {
  display: flex;
  flex: 1;
  align-items: center;
  margin-left: -20px;
}

.fun-btn button {
  margin-left: 20px;
}

.float-shadow-card:hover {
  box-shadow: 0 12px 20px rgb(0 0 0 / 8%);
  transform: translateY(-4px); /* 上浮 4px */
}
</style>
